<?php

namespace app\api\controller\ai;

use thinkct\controller\Frontend;
use app\common\model\User as UserModel;
use app\common\model\Kami as KamiModel;
use app\common\model\vip\Record as VipRecordModel;
use app\common\model\UserMoneyLog;

class User extends Frontend
{
    protected array $noNeedLogin = ['get_vip'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 保存个人信息
     */
    public function save_info(): void
    {
        $data = $this->request->only(['avatar', 'nickname', 'motto']);
        $user = UserModel::where('id', $this->auth->id)->save($data);

        $this->success('保存成功', [
            'userInfo'  => $this->auth->getUserInfo(),
        ]);
    }


    /**
     * 重置AppToken
     */
    public function reset_app_token(): void
    {
        $user = UserModel::where('id', $this->auth->id)->find();
        $user->app_token = md5(uniqid());
        $user->save();
        $this->success('重置成功', [
            'app_token' => $user->app_token,
        ]);
    }

    /**
     * 卡密充值
     */
    public function recharge_kami(): void
    {
        $code = $this->request->post('code');
        if(!$code) {
            $this->error('卡密不能为空');
        }
        $kami = KamiModel::where('code', $code)->find();
        if(!$kami) {
            $this->error('卡密不存在');
        }
        if($kami['status'] == 1) {
            $this->error('卡密已被使用');
        }
        $user = UserModel::where('id', $this->auth->id)->find();
        $user->money = $user->money + $kami['money'];
        $user->save();
        \app\common\model\UserMoneyLog::create([
            'user_id' => $this->auth->id,
            'money' => $kami['money'],
            'before' => $user->money - $kami['money'],
            'after' => $user->money,
            'memo' => '卡密充值',
        ]);
        $kami->status = 1;
        $kami->save();
        $this->success('充值成功', [
            'money' => $user->money,
        ]);
    }

    public function promotion(): void
    {
        $user = UserModel::where('id', $this->auth->id)->find();
        if ($user->invite_code == '') {
            // 生成邀请码6位英文数字
            $user->invite_code = substr(uniqid(), 2, 6);
            $user->save();
        }

        // 下级用户
        $userPid = UserModel::where('pid', $this->auth->id)->select();

        $this->success('获取成功', [
            'invite_code' => $user->invite_code,
            'promotion' => $userPid,
        ]);
    }

    /**
     * 获取会员套餐
     */
    public function get_vip(): void
    {
        $type = $this->request->get('type');
        $vip = \app\admin\model\ai\Vip::where(['type'=>$type])->select();
        $this->success('获取成功', $vip);
    }

    /**
     * 购买会员套餐
     */
    public function buy_vip(): void
    {
        $id = $this->request->post('id');
        $vip = \app\admin\model\ai\Vip::where(['id'=>$id])->find();

        //if (!cache()->get('sys_auth')) $this->error('免费版不支持购买会员套餐');
        if(!$vip) $this->error('套餐不存在');

        $user = UserModel::where('id', $this->auth->id)->find();
        if($vip['price'] > $user->money) $this->error('余额不足');

        // 扣除余额
        $user->money = $user->money - $vip['price'];
        $user->save();
        \app\common\model\UserMoneyLog::create([
            'user_id' => $this->auth->id,
            'money' => -$vip['price'],
            'before' => $user->money + $vip['price'],
            'after' => $user->money,
            'memo' => '购买会员套餐',
        ]);

        // 判断是否是会员
        $vipRecord = VipRecordModel::where('user_id', $this->auth->id)->find();
        if($vipRecord) {
            $vipRecord->vip_id = $vip['id'];
            $vipRecord->days = $vipRecord->days + $vip['days'];
            $vipRecord->end_time = strtotime('+' . $vip['days'].' day', $vipRecord->end_time);
            $vipRecord->save();
        } else {
            VipRecordModel::create([
                'user_id' => $this->auth->id,
                'vip_id' => $vip['id'],
                'days' => $vip['days'],
                'price' => $vip['price'],
                'end_time' => strtotime('+' . $vip['days'].' day'),
            ]);
        }


        $this->success('购买成功', [
            'money' => $user->money,
            'vip' => $user->vip,
            'vip_end_time' => $user->vip_end_time,
        ]);
    }

    /**
     * 获取会员记录
     */
    public function get_vip_record(): void
    {
        $record = VipRecordModel::where('user_id', $this->auth->id)->select();
        foreach ($record as $key => $value) {
            $record[$key]['name'] = $value['vip']['title'];
            $record[$key]['end_time'] = date('Y-m-d H:i:s', $value['end_time']);
        }

        $this->success('获取成功', $record);
    }

    /**
     * 获取会员消耗记录
     */
    public function get_vip_log(): void
    {
        $limit = $this->request->get('limit', 10);
        $log = \app\admin\model\ai\vip\Log::where('user_id', $this->auth->id)
            ->order('id', 'desc')
            ->limit($limit)
            ->select();
        foreach ($log as $key => $value) {
            $log[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
        }
        $this->success('获取成功', $log);
    }
}